package edu.nf.controller.handler;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Date 2023-05-05
 * @Author 陈
 * 全局异常处理
 */
@WebFilter("/*")
public class GlobalExceptionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            // 放行
            filterChain.doFilter(servletRequest,servletResponse);
        } catch (Exception e) {
            HttpServletRequest req = (HttpServletRequest)servletRequest ;
            // 获取异常信息，并添加到请求作用范围中
            req.setAttribute("error",e.getMessage());
            // 转发页面，进行友好提示
            req.getRequestDispatcher("error.jsp").forward(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
